package com.motionlog.view;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

public class DiagramView extends View {

	private static final String TAG = DiagramView.class.getSimpleName();

	private int mMaxValue = -1;
	private int mDivision = -1;
	private LinkedHashMap<String, Integer> mDatas;

	private Paint mLinePaint;
	private Paint mColumnPaint;
	private Paint mTextPaint;

	public DiagramView(Context context) {
		this(context, null);
	}

	public DiagramView(Context context, AttributeSet attrs) {
		super(context, attrs);

		mLinePaint = new Paint();
		mLinePaint.setColor(Color.GREEN);
		mLinePaint.setStrokeWidth(2);
		mColumnPaint = new Paint();
		mColumnPaint.setColor(Color.BLUE);
		mTextPaint = new Paint();
		mTextPaint.setColor(Color.BLACK);
		mTextPaint.setTextSize(12);
	}

	@Override
	protected void onAttachedToWindow() {
		super.onAttachedToWindow();
	}

	private static final int SHOW_LINE_COUNT = 5;

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);

		android.util.Log.d(TAG, "maxValue: " + mMaxValue + ", division: "
				+ mDivision + ", data: " + mDatas);
		if (mMaxValue <= 0 || mDatas == null) {
			return;
		}

		int height = getHeight() - 20;
		int width = getWidth();
		android.util.Log.d(TAG, "height: " + height + ", width: " + width);
		int padding = 20;
		// 画竖线
		canvas.drawLine(0, 0, 0, height, mLinePaint);

		// 画多条横线
		int division = height / SHOW_LINE_COUNT;
		for (int i = 0; i < SHOW_LINE_COUNT; i++) {
			int y = height - division * i;
			canvas.drawLine(0, y, width, y, mLinePaint);
			canvas.drawText(
					String.valueOf((float) mMaxValue / SHOW_LINE_COUNT * i), 0,
					y, mTextPaint);
		}

		// 画柱子
		int columnWidth = 30;
		int startLeft = (width - columnWidth * 4) / 4 / 2;
		for (Map.Entry<String, Integer> entry : mDatas.entrySet()) {
			if (entry.getValue() > 0) {
				float startY = height - (float) height / (float) mMaxValue
						* (float) entry.getValue();
				canvas.drawRect(startLeft, startY, startLeft + columnWidth,
						height, mColumnPaint);
			}
			canvas.drawText(entry.getKey(), startLeft, height + 10, mTextPaint);
			startLeft += (width - columnWidth * 4) / 4;
		}
	}

	public void setLine(int maxValue) {
		mMaxValue = maxValue;
	}

	public void setData(LinkedHashMap<String, Integer> datas) {
		mDatas = datas;
	}
}
